#ifndef __AMQP_WORKER_H__
#define __AMQP_WORKER_H__

#include <string>
#include <queue>
#include "SimpleAmqpClient/SimpleAmqpClient.h"
#include "json.hpp"

using json = nlohmann::json;

class AmqpWorker
{
private:
	int taskType;
	bool withManager;
	AmqpClient::Channel::ptr_t channel;
	std::string commandQueue, taskQueue;
	std::string taskConsumerTag;
	std::string workerId;

public:
	AmqpWorker(int task_type, bool nomanager=false):
		channel(nullptr), taskType(task_type), withManager(!nomanager) {}
	virtual ~AmqpWorker() {}
	
	bool Connect(const std::string& host, int port, const std::string& username="guest", const std::string& password="guest");
	void Register();
	void Unregister();
	
	void drain_events(int timeout=-1);
	
	struct TaskInfo {
		std::string taskId, url;
		AmqpClient::Envelope::DeliveryInfo deliveryInfo;
	};
	bool pull_task(TaskInfo& task);
	void finish_task(const TaskInfo& task);

protected:
	std::queue<TaskInfo> waiting_tasks, complete_tasks;
	
	bool init_connection();
	void send_message(const json& message);
	bool recv_message(json& message, AmqpClient::Envelope::DeliveryInfo& delivery_info, int timeout);
	
	void onRegisterOK(const std::string& worker_id);
	void onStatus(int statusType);
	void onStop();
	void onTask(const TaskInfo& task);
	
	void startTask(const std::string& task_id);
	void endTask(const std::string& task_id);
};

#endif
